package com.idrive.service;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.LocationManager;
import android.os.IBinder;
import android.widget.Toast;

import com.idrive.database.dao.LocationDataDao;
import com.idrive.listener.PathTrackerListener;

public class PathTrackerService extends Service {
	PathTrackerListener pathTrackerListener = new PathTrackerListener(PathTrackerService.this);

	@Override
	public void onDestroy() {
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Register the listener with the Location Manager to receive location
		// updates
		locationManager.removeUpdates(pathTrackerListener);

		Toast.makeText(this, "iDrive Path Tracker has been stopped....", Toast.LENGTH_LONG).show();

	}

	@Override
	public void onStart(Intent intent, int startid) {

		final LocationDataDao dao = new LocationDataDao(getBaseContext());

		if (dao.getRecordCount() > 0) {

			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("Are you sure do you want to clear existing Path Tracker details before start?")
			        .setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				        public void onClick(final DialogInterface dialog, final int id) {
					        dao.clear();
				        }
			        }).setNegativeButton("No", new DialogInterface.OnClickListener() {
				        public void onClick(final DialogInterface dialog, final int id) {
					        dialog.cancel();
				        }
			        });

			final AlertDialog alert = builder.create();
			alert.show();
		}

		// Acquire a reference to the system Location Manager
		LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Register the listener with the Location Manager to receive location
		// updates
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, pathTrackerListener);

		Toast.makeText(this, "iDrive Path Tracker has been started...", Toast.LENGTH_LONG).show();
	}

	@Override
	public IBinder onBind(Intent intent) {

		return null;
	}
}
